package com.situ.ssh.action;

import com.opensymphony.xwork2.ActionContext;
import com.situ.ssh.common.ServerResponse;
import com.situ.ssh.entity.User;
import com.situ.ssh.service.IUserService;
import com.situ.ssh.util.JSONUtil;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.Map;

//Action交给Spring容器来管理，Spring默认创建实例是singleton,
//但是struts2中每次创建Action都会创建一个新的Action，其实就是
//要求这个Action是多例的，所以要加@Scope("prototype"),告诉
//Spring Action的实例是多例的
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> {

    @Autowired
    private IUserService userService;

    public String list() {
        List<User> list = userService.findAll();
        ActionContext actionContext = ActionContext.getContext();
        Map<String, Object> sessionMap = actionContext.getSession();
        sessionMap.put("list", list);
        return "list";
    }

    public String login() {
        User loginUser = userService.login(model);
        ActionContext actionContext = ActionContext.getContext();
        Map<String, Object> sessionMap = actionContext.getSession();
        sessionMap.put("user", loginUser);
        return "loginSucces";
    }

    public void pageList() {
        if (null != model.getName() && !"".equals(model.getName())){
            detachedCriteria.add(Restrictions.like("name", "%" + model.getName() + "%"));
        }
        // ....继续封装其他的搜索条件

        ServerResponse serverResponse = userService.pageList(searchCondition);

        System.out.println(serverResponse);

        // 将ServerResponse以json格式返回
        JSONUtil.obj2Json(serverResponse);
    }

}
